/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.schedule.core.repository.service;

import cn.hutool.core.lang.Assert;
import info.peigen.hotpot.common.core.enums.YesOrNo;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.component.data.repository.beetlsql.service.AbstractBeetlSqlRepository;
import info.peigen.hotpot.component.schedule.core.domain.ScheduleJob;
import info.peigen.hotpot.component.schedule.core.domain.action.ScheduleJobConvertor;
import info.peigen.hotpot.component.schedule.core.repository.entity.ScheduleJobEntity;
import info.peigen.hotpot.component.schedule.core.repository.mapper.ScheduleJobMapper;
import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.FieldDefaults;
import org.noear.solon.annotation.Component;

/**
 * <b>(ScheduleJobRepository)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2023/1/6
 */
@Data
@EqualsAndHashCode(callSuper = true)
@FieldDefaults(level = AccessLevel.PRIVATE)
@Component
public class ScheduleJobRepository extends AbstractBeetlSqlRepository<ScheduleJobMapper, ScheduleJobEntity> {

    public void store(ScheduleJob domain) {
        ScheduleJobEntity entity = ScheduleJobConvertor.convert(domain);
        mapper.upsert(entity);
    }

    public ScheduleJob active(Integer id) {
        ScheduleJobEntity entity = getMapper().unique(id);

        Assert.notNull(entity, () -> new BusinessException(ResultCode.FAILURE, "激活失败!id=" + id));

        return ScheduleJobConvertor.convert(entity);
    }

    public ScheduleJob active(String jobName) {
        ScheduleJobEntity entity = getMapper().findByJobName(jobName);

        Assert.notNull(entity, () -> new BusinessException(ResultCode.FAILURE, "激活失败!jobName=" + jobName));

        return ScheduleJobConvertor.convert(entity);
    }

    public void changeJobEnableByName(YesOrNo enable, String jobName) {
        getMapper().changeJobEnableByName(enable, jobName);
    }

    public void changeAllJobsEnable(YesOrNo enable) {
        getMapper().changeAllJobsEnable(enable);
    }
}